package com.googlecode.yoohoo.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class IoUtils {
	private static final Log log = LogFactory.getLog(IoUtils.class);

	public static void closeIO(InputStream in) {
		if (in != null) {
			try {
				in.close();
			} catch (Exception e) {
				if (log.isTraceEnabled())
					log.trace("Failed to close the stream.", e);
			}
		}
	}
	
	public static void closeIO(OutputStream out) {
		if (out != null) {
			try {
				out.close();
			} catch (Exception e) {
				if (log.isTraceEnabled())
					log.trace("Failed to close the stream.", e);
			}
		}
	}
	
	public static boolean deleteFileRecursively(File file) {
		if (!file.isDirectory()) {
			return file.delete();
		} else {
			for (File subFile : file.listFiles()) {
				if (!deleteFileRecursively(subFile))
					return false;
			}
			
			return file.delete();
		}
	}

	public static void closeIO(Writer writer) {
		if (writer != null) {
			try {
				writer.close();
			} catch (Exception e) {
				if (log.isTraceEnabled())
					log.trace("Failed to close the writer.", e);
			}
		}
	}
	
	public static void closeIO(Reader reader) {
		if (reader != null) {
			try {
				reader.close();
			} catch (Exception e) {
				if (log.isTraceEnabled())
					log.trace("Failed to close the reader.", e);
			}
		}
	}
	
	public static void writeToFile(File file, String content) throws IOException {
		FileWriter out = null;
		try {
			out = new FileWriter(file);
			out.write(content);
		} catch (IOException e) {
			throw e;
		} finally {
			IoUtils.closeIO(out);
		}
	}
}
